#include "Client.h"
#include "ui_Client.h"

#include "sql.h"
#include "client/client_define.h"

#include "client/upload_file.h"
#include "client/download_file.h"

Client::Client(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Client)
{
    ui->setupUi(this);

    username = "u1";

    sql sql(MYSQL_SERVER_HOST, MYSQL_SERVER_PORT, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DB_NAME);

    if (sql.is_open()) {
        qDebug() << "query u1:";
        sql.select_song_name_and_path("u1");
        qDebug() << "query u3:";
        sql.select_song_name_and_path("u3");
        qDebug() << "query u4:";
        sql.select_song_name_and_path("u4");
    }

    filename = ui->lineEdit_filename->text();

    connect(this->ui->pushButton_openFile, &QPushButton::clicked, this, [&](){
        this->ui->progressBar->setValue(0);
        this->filename = QFileDialog::getOpenFileName(this, "Open a file", "/", "files (*)");
        ui->lineEdit_filename->setText(filename);
    });
    connect(this->ui->pushButton_sendFile, &QPushButton::clicked, this, [&](){
        file_queue.push_back("D:/Desktop/Music/qt-music-player-client/music/ろん,おさむらいさん - step to you.mp3");
        file_queue.push_back("D:/Desktop/Music/qt-music-player-client/music/culicc - 溶けた声で.mp3");
        UploadFile();
    });

    upload_file* upload = new upload_file;
    upload->setUsername(username);
    QThread *thread = new QThread;
    upload->moveToThread(thread); //将任务对象移到子线程中
    connect(this, &Client::file_path, upload, &upload_file::Upload);
    //断开连接
    connect(upload,&upload_file::socket_disconnect,this,[=]()
            {
                //释放资源
                thread->quit();
                thread->wait();
                upload->deleteLater();
                thread->deleteLater();
            });
    //启动线程
    connect(upload, &upload_file::finish, this, [&](){
        timer = new QTimer(this);
        //防止tcp黏包问题,延时20ms
        timer->start(200);
        connect(timer, &QTimer::timeout, [=]()
                {
                    //关闭定时器
                    timer->stop();
                    //发送文件数据
                    UploadFile();
                });

    });
    // connect(upload, &upload_file::finish, this, &Client::UploadFile);
    thread->start();

    download_file *download = new download_file;
    download->setUsername(username);
    QThread *thread2 = new QThread;
    download->moveToThread(thread2); //将任务对象移到子线程中
    connect(this, &Client::snyc_path, download, &download_file::Download);
    connect(this->ui->pushButton_connect, &QPushButton::clicked, this, [&](){
        QString download_path = "D:/Desktop/Music/qt-music-player-client/music";
        emit snyc_path(download_path);
    });
    thread2->start();

}

Client::~Client()
{
}

void Client::disconnectServer()
{
}

void Client::UploadFile() {
    if (file_queue.empty()) return;
    QString file = file_queue.dequeue();
    emit file_path(file);
}

